package com.example.springinit.config;

import com.alibaba.fastjson.JSON;
import com.example.springinit.bean.ResultDto;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;

/**
 * 消息队列产生类
 */
public class ProductMQ {

    private static final Log logger = LogFactory.getLog(ProductMQ.class);

    /**
     * 发送消息
     * @param topic   话题
     * @param tag     标签
     * @param keys    关键词
     * @param message 消息内容
     */
    public static ResultDto sendMessage(String topic, String tag, String keys, String message, int delayLevel) {
        if (message == null) {
            ResultDto resultDto = new ResultDto();
            resultDto.setResult(false);
            resultDto.setErrMsg("消息为空，请检查参数！");
            return resultDto;
        }
        Message msg = new Message(topic, tag, keys, message.getBytes());
        msg.setDelayTimeLevel(delayLevel);
        SendResult sendResult = null;
        ResultDto resultDto = new ResultDto();
        if (msg == null) {
            resultDto.setResult(false);
            resultDto.setErrMsg("消息为空，请检查参数！");
            return resultDto;
        }
        try {
            sendResult = RocketMQConfig.productInstance().send(msg);
        } catch (Exception e) {
            resultDto.setResult(false);
            resultDto.setErrMsg("发送出现MQClientException异常：" + e.getMessage());
            logger.error("发送异常：msg=" + JSON.toJSONString(msg), e);
        }
        if (sendResult == null || !sendResult.getSendStatus().equals(SendStatus.SEND_OK)) {
            resultDto.setResult(false);
            resultDto.setErrMsg("发送出现InterruptedException异常：" + sendResult);
            logger.error("发送异常：msg=" + JSON.toJSONString(msg), new MQClientException(999,sendResult.toString()));
        }else {
            resultDto.setResult(true);
            logger.info("发送成功：" + JSON.toJSONString(msg));
        }
        return resultDto;
    }
}
